package top.codedance.iotp.server.net.handle.otherHandle;

import cd.io.netty.channel.ChannelHandlerContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.constent.Command;
import top.codedance.iotp.common.entity.CommonEntity;
import top.codedance.iotp.server.ServerApplication;
import org.apache.log4j.Logger;
import java.nio.charset.StandardCharsets;

public class GetLoadHandle implements Runnable {
    private static Logger logger = ServerApplication.getLogger(GetLoadHandle.class);

    private ChannelHandlerContext channelHandlerContext;
    private CommonEntity commonEntity;
    public GetLoadHandle(ChannelHandlerContext channelHandlerContext, CommonEntity commonEntity){
        this.channelHandlerContext = channelHandlerContext;
        this.commonEntity = commonEntity;
    }

    @Override
    public void run() {
        byte[] body = commonEntity.getBody();
        String jsonStr = new String(body, StandardCharsets.UTF_8);
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String deviceId = jsonObject.getString("deviceId");
        String loadInfo = ServerApplication.clientsLoadInfo.get(deviceId);
        if(loadInfo != null && !loadInfo.isEmpty()) {
            receive(loadInfo);
            logger.debug("Send client[" + deviceId + "] load infomation: " + loadInfo);
        }
    }

    public void receive(String loadInfo) {
        try{
            CommonEntity commonEntity2 = new CommonEntity();
            commonEntity2.setCommand(Command.GET_LOAD_RECEIVE);
            commonEntity2.setBody(loadInfo.getBytes(StandardCharsets.UTF_8));
            channelHandlerContext.writeAndFlush(commonEntity2.build());
        } catch (Exception e){
            logger.debug(e.getMessage());
        }
    }
}
